<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Serviceorder as OrderModel;
use think\Config;
use think\Db;
use think\Exception;

/**
 * 搭子处理相关接口
 */
class PlaymateOrder extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     */
    public function test()
    {
        //模拟登录
        $this->auth->direct(2);
        $res = $this->auth->getUserinfo();
        $this->success('返回成功', $res);
    }


    /**
     * 接单
     * @param string order_id Y 订单id
     */
    public function receivingOrder()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 1){
            $this->error('订单状态不匹配!');
        }

        $res = db('service_order')->where($where)->update(['status' => 2]);
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');

    }

    /**
     * 拒绝订单
     * @param string order_id Y 订单id
     */
    public function refuseOrder()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 1){
            $this->error('订单状态不匹配!');
        }

        $res = db('service_order')->where($where)->update(['status' => '-1']);
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');

    }

    /**
     * 出发
     * @param string order_id Y 订单id
     */
    public function startOrder()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 2){
            $this->error('订单状态不匹配!');
        }

        $res = db('service_order')->where($where)->update(['status' => '3']);
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');

    }


    /**
     * 确认到达
     * @param string order_id Y 订单id
     * @param string reach_address Y 到达地址
     * @param string reach_lng Y 到达经度
     * @param string reach_lat Y 到达纬度
     * @param string reach_image Y 到达图片
     */
    public function reachOrder()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $reach_address = $this->request->post('reach_address');
        $reach_lng = $this->request->post('reach_lng');
        $reach_lat = $this->request->post('reach_lat');
        $reach_image = $this->request->post('reach_image');

        if (!$order_id || !$reach_address || !is_numeric($reach_lng) || !is_numeric($reach_lat) || !$reach_image){
            $this->error('参数错误!');
        }

        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 3){
            $this->error('订单状态不匹配!');
        }

        $data = [
            'status' => 4,
            'reach_address' => $reach_address,
            'reach_lng' => $reach_lng,
            'reach_lat' => $reach_lat,
            'reach_image' => $reach_image,
            'reach_time' => time(),
        ];

        $res = db('service_order')->where($where)->update($data);
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');
    }


    /**
     * 开始服务
     * @param string order_id Y 订单id
     * @param string start_address Y 开始服务地址
     * @param string start_lng Y 开始服务经度
     * @param string start_lat Y 开始服务纬度
     * @param string start_image Y 开始服务图片
     */
    public function startService()
    {
        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $start_address = $this->request->post('start_address');
        $start_lng = $this->request->post('start_lng');
        $start_lat = $this->request->post('start_lat');
        $start_image = $this->request->post('start_image');

        if (!$order_id || !$start_address || !is_numeric($start_lng) || !is_numeric($start_lat) || !$start_image){
            $this->error('参数错误!');
        }

        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 4){
            $this->error('订单状态不匹配!');
        }

        $data = [
            'status' => 5,
            'start_address' => $start_address,
            'start_lng' => $start_lng,
            'start_lat' => $start_lat,
            'start_image' => $start_image,
            'start_time' => time(),
        ];

        $res = db('service_order')->where($where)->update($data);
        if (!$res){
            $this->error('系统执行异常!');
        }
        $this->success('ok');
    }



    /**
     * 完成服务
     * @param string order_id Y 订单id
     * @param string complete_address Y 完成服务地址
     * @param string complete_lng Y 完成服务经度
     * @param string complete_lat Y 完成服务纬度
     * @param string complete_image Y 完成服务图片
     */
    public function completeService()
    {

        $user_id = $this->auth->id;
        $order_id = $this->request->post('order_id');
        $complete_address = $this->request->post('complete_address');
        $complete_lng = $this->request->post('complete_lng');
        $complete_lat = $this->request->post('complete_lat');
        $complete_image = $this->request->post('complete_image');

        if (!$order_id || !$complete_address || !is_numeric($complete_lng) || !is_numeric($complete_lat) || !$complete_image){
            $this->error('参数错误!');
        }

        $where = [];
        $where['id'] = $order_id;
        $where['expert_user_id'] = $user_id;
        $orderInfo = db('service_order')->where($where)->field('id,user_id,expert_user_id,price,fare_price,status')->find();
        if (!$orderInfo){
            $this->error('参数错误!');
        }

        if ($orderInfo['status'] != 5){
            $this->error('订单状态不匹配!');
        }

        //查询达人信息
        $expertInfo = db('expert')->where(['user_id' => $user_id])->field('id,money')->find();
        if (!$expertInfo){
            $this->error('参数错误!');
        }

        Db::startTrans();
        try {

            //更新订单
            $data = [
                'status' => 6,
                'complete_address' => $complete_address,
                'complete_lng' => $complete_lng,
                'complete_lat' => $complete_lat,
                'complete_image' => $complete_image,
                'complete_time' => time(),
            ];
            db('service_order')->where($where)->update($data);
            //更新订单结束--------------------


            //增加达人金额和记录
            $expert_money = round($orderInfo['price']  * config('site.expert_ratio') / 100 + $orderInfo['fare_price'] , 2); //计算达人佣金
            $log = [
                'expert_id' => $expertInfo['id'],
                'user_id' => $user_id,
                'type' => 1,
                'from_user_id' => $orderInfo['user_id'],
                'from_order_id' => $order_id,
                'money' => $expert_money,
                'before' => $expertInfo['money'],
                'after' => round($expertInfo['money'] + $expert_money, 2),
                'createtime' => time()
            ];
            db('expert_money_log')->insert($log);  //余额记录
            db('expert')->where(['user_id' => $user_id])->setInc('money', $expert_money);  //增加余额
            db('expert')->where(['user_id' => $user_id])->setInc('all_money', $expert_money);  //增加累计余额
            //增加达人金额和记录结束--------------------


            //增加分享达人的分销商金额和记录
            $expert_user_info = db('user')->where(['id' => $user_id])->field('id,agent_user_id')->find(); //查询达人是否有分销商
            if ($expert_user_info && $expert_user_info['agent_user_id']){

                $expert_agent_info  = db('user')->where(['id' => $expert_user_info['agent_user_id']])->field('id,money')->find(); //查询达人分销商
                $expert_agent_money = round($orderInfo['price'] * config('site.expert_agent_ratio') / 100 , 2); //计算达人分销商佣金
                if ($expert_agent_info && $expert_agent_money > 0){
                    $expert_agent_log = [
                        'user_id' => $expert_agent_info['id'],
                        'type' => 2,
                        'from_user_id' => $orderInfo['user_id'],
                        'from_order_id' => $order_id,
                        'money' => $expert_agent_money,
                        'before' => $expert_agent_info['money'],
                        'after' => round($expert_agent_info['money'] + $expert_agent_money, 2),
                        'createtime' => time()
                    ];
                    db('user_money_log')->insert($expert_agent_log);  //余额记录
                    db('user')->where(['id' => $expert_agent_info['id']])->setInc('money', $expert_agent_money);  //增加余额
                }
            }
            //增加达人分销商金额和记录结束--------------------


            //增加分享用户的分销商金额和记录
            $user_info = db('user')->where(['id' => $orderInfo['user_id']])->field('id,agent_user_id')->find(); //查询用户是否有分销商
            if ($user_info && $user_info['agent_user_id']) {

                $user_agent_info = db('user')->where(['id' => $user_info['agent_user_id']])->field('id,money')->find(); //查询用户分销商
                $user_agent_money = round($orderInfo['price'] * config('site.user_agent_ratio') / 100, 2); //计算用户分销商佣金
                if ($user_agent_info && $user_agent_money > 0){

                    $user_agent_log = [
                        'user_id' => $user_agent_info['id'],
                        'type' => 2,
                        'from_user_id' => $orderInfo['user_id'],
                        'from_order_id' => $order_id,
                        'money' => $user_agent_money,
                        'before' => $user_agent_info['money'],
                        'after' => round($user_agent_info['money'] + $user_agent_money, 2),
                        'createtime' => time()
                    ];
                    db('user_money_log')->insert($user_agent_log);  //余额记录
                    db('user')->where(['id' => $user_agent_info['id']])->setInc('money', $user_agent_money);  //增加余额
                }
            }
            //增加用户分销商金额和记录结束--------------------

            Db::commit();
        }catch (Exception $e) {
            print_r($e->getMessage());
            Db::rollback();
            $this->error('系统执行异常!');
        }
        $this->success('ok');
    }



    /**
     * 订单列表
     *
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="string", required=false, description="分页页码, 默认1")
     * @ApiParams (name="limit", type="string", required=false, description="分页, 每页数据条数, 默认10")
     * @ApiParams (name="status", type="string", required=true, description="订单状态")
     */
    public function list()
    {
        $user = $this->auth->getUser();
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $status = $this->request->post('status', '');
        $model = new OrderModel();
        if ($status !== '') {
            if ($status == 2){
                $model = $model->where('status', 'in', [2,3,4]);
            }else{
                $model = $model->where('status', $status);
            }
        }
        $model = $model->where('expert_user_id', $user['id']);
        $data = $model
//            ->field('id,order_sn,price,fare_price,real_price,refund_price,status,service_date,service_time')
            ->with(['detail', 'detail.service',])
            ->page($page, $limit)->order('createtime', 'desc')
            ->select();
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 订单详情
     *
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="string", required=true, description="订单id")
     */
    public function detail()
    {
        $user = $this->auth->getUser();
        $id = $this->request->post('order_id');
        if (empty($id)) {
            $this->error(__('Invalid parameters'));
        }
        $orderModel = new OrderModel();
        $order = $orderModel->with(['detail', 'detail.service', 'address'])->where('id', $id)->where('expert_user_id', $user['id'])->find();
        if (!$order) {
            $this->error(__('Order not exist'));
        }
        $data = $order;
        $this->success(__('Operation completed'), $data);
    }



}
